package com.edu.hre.struts.action.recruit;

import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreJobCandidate;
import com.edu.hre.db.pojo.HreJobCandidatePicture;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.recruit.CandidateAddForm;

public class CandidateAddAction extends Action {

	private static final Logger logger = Logger.getLogger(CandidateAddAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private final String ACTION_NAME = "candidateAdd";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		CandidateAddForm beanForm = (CandidateAddForm) form;
		beanForm.setIsAddNew(false); 
		
		if(request.getParameter(StringConstants.BTN_ADD) == null){

			initFormBean(beanForm, request);
			beanForm.setMessage(StringConstants.BLANK);
			return mapping.findForward(ACTION_NAME);
		}
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm, request);
			return mapping.findForward(ACTION_NAME);
		}
		
		HreJobCandidate tmp = new HreJobCandidate();
		tmp.setFirstName(CommonUtils.normalizeString(beanForm.getFirstName()));
		tmp.setMiddleName(CommonUtils.normalizeString(beanForm.getMiddleName()));
		tmp.setLastName(CommonUtils.normalizeString(beanForm.getLastName()));
		tmp.setEmail(CommonUtils.normalizeString(beanForm.getEmail()));
		tmp.setContactNumber(CommonUtils.normalizeString(beanForm.getContactNumber()));
		tmp.setGender(beanForm.getGender());
		tmp.setIsDeleted(false);
		tmp.setDateCreated(new Date());
		tmp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(tmp);
		if (!status) {
			beanForm.setMessage(StringConstants.INSERT_FAILURE_MESSAGE);
			initFormBean(beanForm, request);
			return mapping.findForward(ACTION_NAME);
		}

		FormFile myFile = beanForm.getImage();
		if(myFile != null && StringUtils.isNotBlank(myFile.getFileName())){
			HreJobCandidatePicture picture = baseService.getFirstPojo("candidateId", Compare.EQUAL, tmp.getId(), null, null, 0, HreJobCandidatePicture.class);
			if(picture == null){
				picture = new HreJobCandidatePicture();
			}
			picture.setCanFileType(myFile.getContentType());
			picture.setCandidateId(tmp.getId());
			picture.setCanFileSize(String.valueOf(myFile.getFileSize()));
			picture.setDateModified(new Date());
			picture.setDateCreated(new Date());
			picture.setCanFileName(myFile.getFileName());
			picture.setCanPicture(myFile.getFileData());

			String w = null;
			String h = null;
			try {
				Image imgTemp = ImageIO.read(new ByteArrayInputStream(myFile.getFileData()));
				w = imgTemp.getWidth(null) + StringConstants.BLANK;
				h = imgTemp.getHeight(null) + StringConstants.BLANK;				
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
			picture.setCanFileWidth(w);
			picture.setCanFileHeight(h);
			baseService.saveOrUpdate(picture);
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}
	
	private void initFormBean(CandidateAddForm beanForm, HttpServletRequest request) {
		
		beanForm.setAllGenders(ComboBoxInit.getAllGenders(true));
	}
	
	private String validateForm (CandidateAddForm beanForm) {
		
		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getFirstName()))){
			return "First name cannot be blank!";
		}

		if(StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getLastName()))){
			return "Last name cannot be blank!";
		} 
		
		if (!StringUtils.isBlank(CommonUtils.normalizeString(beanForm.getEmail())) && !CommonUtils.verifyEmail(CommonUtils.normalizeString(beanForm.getEmail()))) {
			return "Email address is not valid!";
		}

		FormFile myFile = beanForm.getImage();
		if(myFile != null && StringUtils.isNotBlank(myFile.getFileName())){
			if(myFile.getFileSize() > 2097152){
				return "Image file size is too big! (< 2MB required)";
			} else if(!"image/jpeg".equalsIgnoreCase(myFile.getContentType())){
				return "Invalid file type! Only JPEG or PNG files are accepted!";
			}
		}

		return StringConstants.BLANK;
	}
}
